<template>
  <div>
    <a-modal
      :visible="visible"
      title="保存到"
      :bodyStyle="{
        padding: '10px 20px',
      }"
      width="1000px"
      @cancel="cancelClick"
      destroyOnClose
    >
      <template #footer>
        <a-row>
          <div
            style="display: flex; align-items: center; margin-bottom: 20px"
            v-if="materialType != 'text' && jobCategory != 'videoSplit'"
          >
            <div>素材名称：</div>
            <a-input
              v-model:value="autoName"
              placeholder="请输入素材名称"
              allowClear
              style="width: 895px"
            />
          </div>
          <a-col style="width: 100%; text-align: right">
            <a-space>
              <a-button @click="cancelClick" style="border-radius: 5px"
                >取消</a-button
              >

              <a-button
                v-if="aisave == true"
                style="border-radius: 5px"
                type="primary"
                :loading="loading"
                @click="saveFn"
                >确认</a-button
              >
              <a-button
                v-else-if="StoryboardSplit == true"
                style="border-radius: 5px"
                type="primary"
                :loading="loading"
                @click="saveStoryboardSplit"
                >确认</a-button
              >
              <a-button
                v-else
                style="border-radius: 5px"
                type="primary"
                :loading="loading"
                @click="submitClick"
                >确认</a-button
              >
            </a-space>
          </a-col>
        </a-row>
      </template>

      <a-tabs v-model:activeKey="activeKey" @change="activeKeyChange">
        <a-tab-pane v-for="item in tabList" :key="item.key" :tab="item.tab" />
      </a-tabs>
      <!-- 项目素材 -->
      <a-row v-if="activeKey == 1">
        <a-col :span="8" class="xiangmu_mater">
          <div class="xiangmu_mater_box">
            <div style="flex: 1">
              <div v-if="treeData.length">
                <a-input-search
                  v-model:value="seatchValue"
                  placeholder="请输入项目名称搜索"
                  @search="onSearch"
                />
                <a-divider style="margin: 15px 0" />
              </div>
              <a-spin tip="加载中..." :spinning="spinning">
                <a-tree
                  class="draggable-tree"
                  v-model:selectedKeys="selectedKeys"
                  v-model:expandedKeys="expandedKeys"
                  block-node
                  :height="450"
                  :tree-data="treeData"
                  :fieldNames="fieldNames"
                  @select="selectChange"
                  v-if="treeData.length"
                >
                </a-tree>
                <div v-else>
                  <a-empty :image="simpleImage" />
                </div>
              </a-spin>
            </div>
            <!-- 只有当没有数据的时候才显示 -->
            <a-button
              v-if="!(Array.isArray(treeData) && treeData.length)"
              size="mini"
              class="add-mater"
              @click="businessVisible = true"
            >
              <PlusOutlined />新增项目库
            </a-button>
          </div>
        </a-col>
        <a-col :span="16" class="right-content hide-scroller-bar">
          <a-spin tip="加载中..." :spinning="spinningFile">
            <a-row :gutter="[16, 1]" :wrap="true">
              <!-- 新建文件夹 -->
              <a-col>
                <div class="auto-file" v-if="!showMaterial">
                  <div class="auto-file-box">
                    <folderList
                      @newFolder="newSubFolder"
                      :isLoading="folderLoading"
                      :list="folderData"
                      @choose="chooseFolder"
                      :noupload = "true"
                    />
                  </div>
                </div>
              </a-col>
              <a-col
                v-for="item in folderList"
                :key="item.id"
                @click="folderClick(item)"
              >
                <div
                  class="auto-file"
                  :class="folderId == item.id ? 'auto-border' : ''"
                >
                  <div>
                    <cu-icon
                      class="icon"
                      type="icon-wenjianjia1"
                      style="font-size: 60px"
                    />
                  </div>
                  <div class="folder_name">{{ item.folder_name }}</div>
                  <a-badge
                    v-if="
                      item?.statck_multimedias_count || item?.statck_texts_count
                    "
                    :count="
                      item?.statck_multimedias_count || item?.statck_texts_count
                    "
                    class="badge1"
                    style="background: rgba(0, 0, 0, 0.2)"
                  ></a-badge>
                  <div class="icon-contont">
                    <cu-icon
                      v-if="item?.folder_type == 'audio'"
                      class="icon-postion"
                      type="icon-yuyin"
                      style="font-size: 24px"
                    />
                    <cu-icon
                      v-if="item?.folder_type == 'image'"
                      class="icon-postion"
                      type="icon-tupian1"
                      style="font-size: 24px"
                    />
                    <cu-icon
                      v-if="item?.folder_type == 'text'"
                      class="icon-postion"
                      type="icon-zhinengwenan"
                      style="font-size: 24px"
                    />
                    <cu-icon
                      v-if="item?.folder_type == 'video'"
                      class="icon-postion"
                      type="icon-shipin"
                      style="font-size: 24px"
                    />
                  </div>
                </div>
              </a-col>
            </a-row>
            <!-- <a-empty v-else :image="simpleImage" /> -->
          </a-spin>
        </a-col>
      </a-row>

      <!-- 通用素材 -->
      <a-row v-else>
        <a-row
          :gutter="[16, 16]"
          v-if="folderList.length"
          class="content hide-scroller-bar"
        >
          <!-- 新建文件夹 -->
          <a-col>
            <div class="auto-file" v-if="!showMaterial">
              <div class="auto-file-box">
                <folderList
                  @newFolder="newSubFolder"
                  :isLoading="folderLoading"
                  :list="folderData"
                  @choose="chooseFolder"
                />
              </div>
            </div>
          </a-col>
          <a-col v-for="item in folderList" :key="item.id">
            <div
              @click="folderClick(item)"
              class="auto-file"
              :class="folderId == item.id ? 'auto-border' : ''"
            >
              <div>
                <cu-icon
                  class="icon"
                  type="icon-wenjianjia1"
                  style="font-size: 60px"
                />
              </div>
              <div class="folder_name">{{ item.folder_name }}</div>
              <a-badge
                v-if="
                  item?.statck_multimedias_count || item?.statck_texts_count
                "
                :count="
                  item?.statck_multimedias_count || item?.statck_texts_count
                "
                class="badge1"
                style="background: rgba(0, 0, 0, 0.2)"
              ></a-badge>
              <div class="icon-contont">
                <cu-icon
                  v-if="item?.folder_type == 'audio'"
                  class="icon-postion"
                  type="icon-yuyin"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'image'"
                  class="icon-postion"
                  type="icon-tupian1"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'text'"
                  class="icon-postion"
                  type="icon-zhinengwenan"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'video'"
                  class="icon-postion"
                  type="icon-shipin"
                  style="font-size: 24px"
                />
              </div>
            </div>
          </a-col>
        </a-row>
        <a-col :span="24" v-else style="text-align: center">
          <a-empty :image="simpleImage" />
        </a-col>
      </a-row>
    </a-modal>

    <!-- 新建文件夹 -->
    <NewFolder
      :isFlaking="isFlaking"
      :visible="addVisible"
      @onCancel="addVisible = false"
      @onSubmit="closeAdd"
      :current_name="current_name"
      :checkedSelectType="materialType"
      :defaultData="{ type: materialType, isDisable: true }"
      :groupData="{
        id: expandedKeys,
        default_group_id: currentLibrary.groupid,
        merchant_library_id: currentLibrary.merchant_library_id,
      }"
    />
  </div>

  <!-- 新增项目库 -->
  <NewMerchant
    :visible="businessVisible"
    @onCancel="businessVisible = false"
    @onSubmit="closeBUsinessModal"
  />
</template>

<script>
import { defineComponent, reactive, toRefs, watch } from "vue";
import NewFolder from "@/views/shotstack/MaterialCenter/modules/NewFolder.vue";
import folderList from "@/views/shotstack/EditingCenter/modules/bottomSet/components/folderList.vue";
import { Form, message, Empty } from "ant-design-vue";
import request from "../../../../common/utils/request";
import { defineEmits } from "vue";
// 新增项目库按钮
import NewMerchant from "@/views/shotstack/MaterialCenter/modules/NewMerchant.vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { param } from "jquery";

export default defineComponent({
  name: "materialsModule",
  components: {
    NewFolder,
    folderList,
    PlusOutlined,
    NewMerchant,
  },
  props: {
    // aisave : {
    //   type: Boolean,
    //   default: false,
    // },
    visible: {
      type: Boolean,
      default: true,
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    material_type: {
      type: String,
      default: "audio",
    },
    jobCategory: {
      type: String,
      default: "",
    },
    tabHidden: {
      default: -1,
      type: Number,
    },
    // true 会emit('selfRequest'), false 不触发
    requestType: {
      type: Boolean,
      default: false,
    },
    aisave: {
      type: Boolean,
      default: false,
    },
    StoryboardSplit: {
      type: Boolean,
      default: false,
    },
    isFlaking: {
      type: Boolean,
      default: false,
    },
    splitVideoId: {
      type: Number,
      default: null,
    },
    clip_points: {
      type: Array,
      default: [],
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      count: 0,
      activeKey: 1,
      seatchValue: "",
      treeData: [],
      fieldNames: {
        children: "folder_group",
        title: "name",
        key: "id",
      },
      MemberName: "",
      Checked_groupid: "",
      default_group_id: "",
      beforeDash: "",
      selectedKeys: [],
      expandedKeys: [],
      spinning: false,
      spinningFile: false,
      folderList: [],
      folderId: 0,
      groupId: 0,
      autoName: "",
      merchant_library_id: "",
      loading: false,
      // 控制新增文件夹显示隐藏
      addVisible: false,
      // 当前素材库
      currentLibrary: {},
      // 文件夹加载
      folderLoading: false,
      // 文件夹数据
      folderData: [],
      // 当前文件夹
      currentFolder: {},
      tabList: [
        { key: 1, tab: "项目素材" },
        { key: 2, tab: "通用素材" },
      ],
      // 新增项目库
      businessVisible: false,
      current_name: "",
      materialType:"audio",
    });

    // 关闭前的回调
    const closeAdd = (data) => {
      state.addVisible = false;

      if (state.activeKey == 2) {
        getfolderList(0, 0);
      } else {
        // 获取添加后的文件夹数据

        getWithGroupList();
      }
    };

    const closeBUsinessModal = () => {
      state.businessVisible = false;
      getWithGroupList();
    };

    // 新建文件夹
    const newSubFolder = () => {
      // 这边的id 做了树形结构处理  单独处理
      let huixianLibrary = {};

      state.currentLibrary = state.treeData.flatMap((library) => {
        const foundItemInGroup = library.folder_group.find(
          (item) => item.groupid === state.Checked_groupid
        );
        return foundItemInGroup ? [foundItemInGroup] : [];
      })[0];
      for (const library of state.treeData) {
        const foundItemInGroup = library.folder_group.find(
          (item) => item.id === state.currentLibrary.id
        );

        if (foundItemInGroup) {
          huixianLibrary = library;
          break; // 找到后退出循环
        }
      }

      state.current_name = `${huixianLibrary.name}/${state.currentLibrary?.group_name}`;
      if (state.activeKey == 2) {
        state.current_name = "null";
        state.currentLibrary.groupid = 0;
        state.currentLibrary.merchant_library_id = 0;
      }
      state.addVisible = true;
    };

    // 选择文件夹
    const chooseFolder = (item) => {
      state.currentFolder = item;
      if (item.folder_type == "text") {
        getTextList({ merchant_folder_statck_id: item.id });
      } else {
        getMediaList({ merchant_folder_statck_id: item.id });
      }
      state.showMaterial = true;
    };

    const onSearch = () => {
      getWithGroupList();
    };

    const getWithGroupList = () => {
      let params = {
        name: state.seatchValue || undefined,
      };
      state.spinning = true;
      request
        .get("/work_ai", "/user/shotstack/library/withGroup/list")
        // .get("/work_ai", "/user/shotstack/library/withGroup/list", params)
        .then((res) => {
          if (res.result.length) {
            // if (false) {
            // 这里应该为成片库的
            res.result.forEach((item) => {
              item.folder_group.forEach((folder, index) => {
                folder.id = `${folder.id}-${index}`; //子级id处理 解决数组id一样导致的报错
                folder.name = folder.group_name;
              });
            });

            state.expandedKeys = [res.result[0].id];
            state.selectedKeys = [res.result[0].folder_group[0].id];

            state.treeData = res.result.map((item) => {
              return {
                ...item,
                selectable: false,
              };
            });

            state.treeData = state.treeData.map((item) => ({
              ...item,
              folder_group: item.folder_group.map((groupItem) => ({
                ...groupItem,
                groupid: groupItem.id.split("-")[0],
              })),
            }));

            state.Checked_groupid = state.treeData[0].folder_group[0].groupid;
          } else {
            state.treeData = [];
            state.folderList = [];
          }
          getfolderList(
            res.result[0].id,
            res.result[0].folder_group[0].id.split("-")[0]
          );
          state.spinning = false;
        })
        .catch(() => {
          state.spinning = false;
        });
    };

    const getfolderList = (merchant_library_id, group_id) => {
      let params = {
        folder_use_type: 1,
        material_type: state.materialType,
        merchant_library_id,
        group_id,
      };
      // if (props.isFlaking == true) {
      //   params.folder_use_type = 2;
      // }
      state.spinningFile = true;
      request
        .post("/work_ai", "/user/shotstack/folder/list", params)
        .then((res) => {
          state.folderList = res.result.data;
          state.spinningFile = false;
        })
        .catch(() => {
          state.spinningFile = false;
        });
    };

    const selectChange = (key, e) => {
      state.Checked_groupid = e.node.id.split("-")[0];
      state.folderId = 0;
      getfolderList(e.node.merchant_library_id, e.node.id.split("-")[0]);
    };

    // 选中单个文件夹
    const folderClick = (data) => {
      // 这里能拿到所有id
      state.folderId = data.id;
      state.merchant_library_id = data.id;
      // state.merchant_library_id = data.merchant_library_id;
      state.groupId = data.group_id;
      state.MemberName = data.folder_name;
    };

    const activeKeyChange = (key) => {
      console.log(key, "111111111111来回切换");
      state.folderId = 0;
      state.folderList = [];
      if (key == 1) {
        getWithGroupList();
      } else {
        getfolderList(0, 0);
      }
    };

    const cancelClick = () => {
      emit("onCancel");
      state.MemberName = "";
    };

    // const emit = defineEmits(['updateData', 'callParentMethod']);

    // 拆分保存
    const saveFn = () => {
      if (!state.folderId) {
        message.warn("请选择要保存到的素材目录");
      } else {
        const params = {
          // 视频文件夹id
          merchant_folder_statck_id: state.folderId,
          // 视频id
          id: props.splitVideoId || "",
          // 视频切割点
          clip_points: props.clip_points || "",
        };
        state.loading = true;
        console.log(params);
        request
          .post("/work_ai", "/user/shotstack/video/submit_video_clips", params)
          .then((res) => {
            message.success("保存成功！请等待处理完成!");
            state.loading = false;
            emit("selfRequest");
            state.MemberName = "";
          })
          .catch((err) => {
            console.log(err);
            state.loading = false;
          });
      }
    };

    const saveStoryboardSplit = async () => {
      if (!state.folderId) {
        return message.warn("请选择要保存到的素材目录");
      }

      emit("getMerchant_folder_statck_id", state.folderId);
    };

    // 分镜拆分保存

    const submitClick = () => {
      if (!state.folderId) {
        message.warn("请选择要保存到的素材目录");
        return;
      }

      if (
        !state.autoName &&
        state.materialType != "text" &&
        props.jobCategory != "videoSplit"
      ) {
        message.warn("请输入素材名称");
        return;
      }

      let params = {
        // 新参数
        merchant_folder_statck_id: state.folderId,
        file_urls: [
          {
            material_name: state.autoName,
            material_url: props.data.material_url,
            type: state.materialType,
          },
        ],
      };

      if (props.requestType) {
        emit("selfRequest", params);
        state.loading = true;
        return;
      }

      if (state.materialType != "text") {
        state.loading = true;
        request
          .post("/work_ai", "/material/upload", params)
          .then((res) => {
            state.loading = false;
            message.success("保存成功");
            emit("onSuccess");
          })
          .catch(() => {
            state.loading = false;
          });
      } else {
        let params = {
          material_type: state.materialType,
          merchant_folder_statck_id: state.folderId,
          group_id: state.groupId,
          headline: [props?.data?.material_content],
        };
        state.loading = true;
        request
          .post("/work_ai", "/user/shotstack/text", params)
          .then((res) => {
            state.loading = false;
            message.success("保存成功");
            emit("onSuccess");
          })
          .catch(() => {
            state.loading = false;
          });
      }
    };

    // 获取列表展示数据
    const getWithGroupListFn = () => {
      state.autoName = props.data.autoName || "";
      if (props.tabHidden > 0) {
        let hiddenTabIndex = state.tabList.findIndex(
          (item) => item.key == props.tabHidden
        );
        hiddenTabIndex != -1 && state.tabList.splice(hiddenTabIndex, 1);
        state.activeKey = state.tabList[0].key;
        activeKeyChange(state.activeKey);
        return;
      }
      getWithGroupList();
    };
    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.materialType = props.material_type
          getWithGroupListFn();
        } else {
          state.folderId = 0;
          state.autoName = "";
        }
      }
    );

    // 关闭loading
    const stopLoding = () => {
      state.loading = false;
    };

    return {
      ...toRefs(state),
      getWithGroupListFn,
      cancelClick,
      onSearch,
      selectChange,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      folderClick,
      submitClick,
      saveFn,
      activeKeyChange,
      chooseFolder,
      stopLoding,
      newSubFolder,
      closeAdd,
      closeBUsinessModal,
      saveStoryboardSplit,
    };
  },
});
</script>

<style lang="less" scoped>
.folder_name {
  width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.xiangmu_mater {
  padding: 0 20px;
  border-right: 1px solid #efeff5;

  .xiangmu_mater_box {
    display: flex;
    height: 100%;
    flex-direction: column;
    justify-content: space-between;
  }
}

.add-mater {
  width: 100%;
  margin-top: auto;
  font-size: 13px;
}

.auto-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  border-radius: 5px;
  border: 2px solid #ffffff;
  cursor: pointer;
  position: relative;

  .auto-file-box {
    transform: scale(0.9);
    position: absolute;
    top: -20px;
    left: -1px;
  }

  .icon-contont {
    position: absolute;
    top: 41px;
    left: 46px;
  }

  &:hover {
    background: #f2f2f2;
  }

  .badge1 {
    position: absolute;
    top: 13px;
    right: 28px;
    border-radius: 50%;
    color: #fff;
  }

  .badge2 {
    position: absolute;
    top: 13px;
    right: -40px;
    border-radius: 50%;
    color: #fff;
  }

  &.auto-border {
    border: 2px solid #3261fb;
  }
}

.right-content {
  padding: 0 20px;
  height: 370px;
  overflow: auto;
}

.content {
  height: 370px;
  overflow: auto;
}
</style>
